import React, { Suspense, useCallback } from 'react';
import { Canvas } from '@react-three/fiber';
import { Grid, Stats, Sky } from '@react-three/drei';
import Drone from './Drone';
import DroneFormation from './DroneFormation';
import MapEnvironment from './MapEnvironment';
import LoadingFallback from './LoadingFallback';
import EnhancedCameraControls from './EnhancedCameraControls';

const Scene = ({
  animationSpeed,
  showComponents,
  colors,
  showGrid = true,
  showStats = false,
  flightState = null,
  formationState = null,
  showTrails = false,
  showObstacles = true,
  showBoundaries = true,
  showTerrain = true,
  mapSize = 50,
  cameraSettings = {}
}) => {
  const handleCreated = useCallback(({ gl }) => {
    // Handle WebGL context lost
    gl.domElement.addEventListener('webglcontextlost', (event) => {
      console.warn('WebGL context lost. Attempting to restore...');
      event.preventDefault();
    });

    gl.domElement.addEventListener('webglcontextrestored', () => {
      console.log('WebGL context restored successfully.');
    });
  }, []);

  return (
    <div style={{ width: '100%', height: '100vh' }}>
      <Canvas
        camera={{
          position: [5, 3, 5],
          fov: 50
        }}
        shadows
        style={{ background: 'linear-gradient(to bottom, #87CEEB, #98FB98)' }}
        onCreated={handleCreated}
        gl={{
          antialias: true,
          alpha: false,
          powerPreference: "high-performance"
        }}
      >
        {/* Enhanced Lighting */}
        <ambientLight intensity={0.4} />

        {/* Main sun light */}
        <directionalLight
          position={[20, 20, 10]}
          intensity={1.5}
          castShadow
          shadow-mapSize-width={4096}
          shadow-mapSize-height={4096}
          shadow-camera-far={100}
          shadow-camera-left={-50}
          shadow-camera-right={50}
          shadow-camera-top={50}
          shadow-camera-bottom={-50}
          shadow-bias={-0.0001}
        />

        {/* Fill lights */}
        <pointLight position={[-15, 10, -15]} intensity={0.3} color="#87CEEB" />
        <pointLight position={[15, 10, 15]} intensity={0.3} color="#FFE4B5" />

        {/* Ground bounce light */}
        <hemisphereLight
          skyColor="#87CEEB"
          groundColor="#2d5a27"
          intensity={0.4}
        />

        {/* Sky and Environment */}
        <Sky
          distance={450000}
          sunPosition={[20, 20, 10]}
          inclination={0}
          azimuth={0.25}
        />

        {/* Simple gradient background */}
        <color attach="background" args={['#87CEEB']} />

        {/* Fog for depth */}
        <fog attach="fog" args={['#87CEEB', 30, 100]} />

        {/* Map Environment with obstacles and boundaries */}
        <Suspense fallback={<LoadingFallback message="Loading Environment..." />}>
          <MapEnvironment
            showObstacles={showObstacles}
            showBoundaries={showBoundaries}
            showTerrain={showTerrain}
            mapSize={mapSize}
          />
        </Suspense>

        {/* Grid */}
        {showGrid && (
          <Grid
            args={[mapSize / 2, mapSize / 2]}
            cellSize={2}
            cellThickness={0.3}
            cellColor="#4a5a4a"
            sectionSize={10}
            sectionThickness={0.8}
            sectionColor="#6a7a6a"
            fadeDistance={mapSize}
            fadeStrength={1}
            followCamera={false}
            infiniteGrid={false}
          />
        )}

        {/* Main Drone Model */}
        <Suspense fallback={<LoadingFallback message="Loading Drone Model..." />}>
          <Drone
            animationSpeed={animationSpeed}
            showComponents={showComponents}
            colors={colors}
            flightState={flightState}
          />
        </Suspense>

        {/* Formation Drones */}
        <Suspense fallback={<LoadingFallback message="Loading Formation..." />}>
          <DroneFormation
            formationState={formationState}
            mainDroneState={flightState}
            showComponents={showComponents}
            animationSpeed={animationSpeed}
            showTrails={showTrails}
          />
        </Suspense>

        {/* Enhanced Camera Controls */}
        <EnhancedCameraControls
          enablePan={cameraSettings.enablePan ?? true}
          enableZoom={cameraSettings.enableZoom ?? true}
          enableRotate={cameraSettings.enableRotate ?? true}
          minDistance={cameraSettings.minDistance ?? 2}
          maxDistance={cameraSettings.maxDistance ?? 50}
          autoRotate={cameraSettings.autoRotate ?? false}
          autoRotateSpeed={cameraSettings.autoRotateSpeed ?? 0.5}
          panSpeed={cameraSettings.panSpeed ?? 1}
          rotateSpeed={cameraSettings.rotateSpeed ?? 1}
          zoomSpeed={cameraSettings.zoomSpeed ?? 1}
          smoothness={cameraSettings.smoothness ?? 0.1}
          target={cameraSettings.target ?? [0, 0, 0]}
        />

        {/* Performance Stats */}
        {showStats && <Stats />}
      </Canvas>
    </div>
  );
};

export default Scene;
